package com.hxh.wechat.util

import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat.startActivity
import com.google.gson.Gson
import com.google.gson.JsonArray
import com.google.gson.JsonObject
import com.hxh.wechat.activity.Login
import com.hxh.wechat.constant.GlobalConstant
import com.hxh.wechat.model.Msg
import com.hxh.wechat.model.UserInfo
import org.webrtc.ContextUtils.getApplicationContext


class DBUtil {
    companion object {
        fun getGson(): Gson {
            return Gson()
        }

        fun popMsg(msg: String, con: Context) {
            Toast.makeText(
                con, msg,
                Toast.LENGTH_SHORT
            ).show()
        }

        fun parseObjString(responseData: String): JsonObject? {
            return getGson().fromJson(responseData, JsonObject::class.java)
                .getAsJsonObject("data")
        }

        fun parseStatusString(responseData: String): String? {
            return getGson().fromJson(responseData, JsonObject::class.java).get("status").toString()
        }

        fun parseArrayString(responseData: String): JsonArray? {
            return getGson().fromJson(responseData, JsonObject::class.java)
                .getAsJsonArray("data")
        }

        fun getDB(con: Context): SharedPreferences? {
            return con.getSharedPreferences("SpQing", Context.MODE_PRIVATE)
        }

        fun setData(con: Context, key: String, responseData: String) {
            getDB(con)?.edit()?.putString(key, responseData)?.apply()
        }


        fun getUser(con: Context): UserInfo? {
            return getGson().fromJson(
                getDB(con)?.getString(GlobalConstant.USER_INFO, "无数据"),
                UserInfo::class.java
            );

        }

        fun getData(con: Context, key: String): String? {
            return getDB(con)?.getString(key, "无数据");
        }

        fun parseMsg(text: String): Msg? {
            return getGson().fromJson<Msg>(
                getGson().fromJson(text, JsonObject::class.java).getAsJsonObject("msg"),
                Msg::class.java
            )
        }

        fun parseExtand(text: String): String? {
            return getGson().fromJson(text, JsonObject::class.java).get("extand").toString()
        }

        fun logout(con: Context?, activity: AppCompatActivity) {
            setData(con!!, GlobalConstant.USER_INFO, "");
            val intent = Intent(activity, Login::class.java)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
            con.startActivity(intent)
            activity.finish();
        }
    }
}